package com.maixy.studyonlineapi.apis;


import com.maixy.studyonlineapi.bean.State;
import com.maixy.studyonlineapi.constants.GlobalConstant;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName CommonResult
 * @Description 统一API响应结果封装
 * @Date 2020/4/13 13:34
 * @Author mai
 */
public class ApiResponse implements Serializable {


    private Map<String, Object> data;

    private State state;

    public Map<String, Object> getData() {
        return data;
    }

    public void setData(Map<String, Object> data) {
        if (null != this.data) {
            this.data.putAll(data);
        } else {
            this.data = data;
        }
    }

    public State getState() {
        return state;
    }

    public void setState(State state) {
        this.state = state;
    }

    public ApiResponse addValueToData(String key, Object value) {
        if (this.data == null) {
            this.data = new HashMap<>();
        }
        this.data.put(key, value);
        return this;
    }

    public <T> ApiResponse addListToData(List<T> list) {
        return this.addListToData("dataList", list);
    }

    public <T> ApiResponse addListToData(String key, List<T> list) {
        if (this.data == null) {
            this.data = new HashMap<>();
        }
        if (list == null) {
            list = new ArrayList<T>();
        }
        this.data.put(key, list);
        return this;
    }

    public static ApiResponse ok() {
        ApiResponse response = new ApiResponse();
        response.setState(GlobalConstant.StateCode.SUCCESS);
        response.setData(new HashMap<>());
        return response;
    }

    public static ApiResponse ok(Map<String, Object> data) {
        ApiResponse response = new ApiResponse();
        response.setState(GlobalConstant.StateCode.SUCCESS);
        response.setData(data);
        return response;
    }

    public static ApiResponse error() {
        ApiResponse response = new ApiResponse();
        response.setState(GlobalConstant.StateCode.FAILURE);
        response.setData(new HashMap<>());
        return response;
    }

    public static ApiResponse error(State state) {
        ApiResponse response = new ApiResponse();
        response.setState(state);
        response.setData(new HashMap<>());
        return response;
    }
}
